<template>
    <div class="data-apply-container">
        <!-- 列表页 -->
        <div v-if="!showDetail">
            <!-- 搜索区域 -->
            <div class="filter-area">
                <el-form :inline="true" :model="searchForm" class="search-form-container">
                    <el-form-item label="工单编号" class="form-item">
                    <el-input 
                        v-model="searchForm.orderNumber" 
                        placeholder="输入工单编号" 
                        clearable 
                        style="width: 180px"/>
                    </el-form-item>
                    
                    <el-form-item label="审批人" class="form-item">
                    <el-select 
                        v-model="searchForm.userId" 
                        placeholder="选择审批人"
                        filterable
                        clearable
                        style="width: 180px">
                        <el-option 
                        v-for="user in provinceUsers" 
                        :key="user.userId" 
                        :label="user.userName"
                        :value="user.userId"
                        />
                    </el-select>
                    </el-form-item>
                    
                    <el-form-item label="审批状态" class="form-item">
                    <el-select 
                        v-model="searchForm.status" 
                        placeholder="选择审批状态" 
                        clearable
                        style="width: 180px"
                    >
                        <el-option label="待审批" value="1"/>
                        <el-option label="已通过" value="2"/>
                        <el-option label="已拒绝" value="3"/>
                    </el-select>
                    </el-form-item>
                    
                    <el-form-item label="批次号" class="form-item">
                    <el-input 
                        v-model="searchForm.batchNumber" 
                        placeholder="输入批次号" 
                        clearable 
                        style="width: 180px"
                    />
                    </el-form-item>
                    
                    <el-form-item label="创建时间" class="form-item">
                    <el-date-picker 
                        v-model="searchForm.createTimeRange" 
                        type="daterange" 
                        range-separator="至"
                        start-placeholder="开始日期" 
                        end-placeholder="结束日期" 
                        value-format="YYYY-MM-DD"
                        style="width: 280px"/>
                    </el-form-item>
                    
                    <el-form-item label="审批时间" class="form-item">
                    <el-date-picker 
                        v-model="searchForm.approvalTimeRange" 
                        type="daterange" 
                        range-separator="至"
                        start-placeholder="开始日期" 
                        end-placeholder="结束日期" 
                        value-format="YYYY-MM-DD"
                        style="width: 280px"
                    />
                    </el-form-item>
                    
                    <el-form-item class="form-actions">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                        <el-button type="primary" @click="showApplyDialog"><el-icon><Plus /></el-icon>取数申请</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 标签页 -->
            <el-tabs v-model="activeTab" @tab-click="handleTabChange">
                <el-tab-pane label="待审核" name="pending"></el-tab-pane>
                <el-tab-pane label="已完成" name="completed"></el-tab-pane>
                <el-tab-pane label="全部" name="all"></el-tab-pane>
            </el-tabs>

            <!-- 数据表格 -->
            <el-table :data="filteredData" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
                <el-table-column prop="orderNumber" label="工单编号" width="180" align="center"></el-table-column>
                <el-table-column prop="templateName" label="模板" width="150" align="center">
                </el-table-column>
                <el-table-column prop="remark" label="申请原因" min-width="200" align="center"></el-table-column>
                <el-table-column label="审批状态" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.status)">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="审批人" width="150" align="center">
                    <template #default="{ row }">
                        {{ getApprovalUsers(row.users) }}
                    </template>
                </el-table-column>
                <!-- 标签等于 待审批的时候隐藏 审批时间、批次号 -->
                <el-table-column v-if="activeTab != 'pending'" prop="approvalTime" label="审批时间" width="180" align="center"></el-table-column>
                <el-table-column v-if="activeTab != 'pending'" label="批次号" width="200" align="center">
                    <template #default="{ row }">
                        {{ row.batchNumber || '-' }}
                    </template>
                </el-table-column>
                <el-table-column prop="createBy" label="申请人" width="120" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
                
                <el-table-column label="操作" width="180" fixed="right" align="center">
                    <template #default="{ row }">
                        <!-- 根据审批状态显示审批按钮 以及校验当前登录人是否是审批人，不是的话不展示按钮 -->
                        <el-button v-if="row.status === '1' && isApprovalUser(row.users)" link type="primary" @click="showApprovalDialog(row)">
                            审批
                        </el-button>
                        <el-button link type="primary" @click="showDetailView(row)">查看详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <div class="pagination-area" style="margin-left: 1012px;">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
                :page-sizes="[10, 20, 30, 50]"
                :page-size="pagination.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total">
                </el-pagination>
            </div>
        </div>

        <!-- 详情页 -->
        <el-card v-if="showDetail" class="detail-card">
            <template #header>
                <div class="detail-header">
                    <el-button link type="primary" icon="ArrowLeft" @click="backToList">返回列表</el-button>
                    <span>取数申请详情</span>

                    <!-- 新增通过和拒绝按钮 -->
                    <div style="margin-left: auto;">
                        <el-button 
                            v-if="currentDetail.status === '1' && isApprovalUser(currentDetail.users)"
                            type="success" 
                            @click="handleApprove(currentDetail)">
                            通过
                        </el-button>
                        <el-button 
                            v-if="currentDetail.status === '1' && isApprovalUser(currentDetail.users)"
                            type="danger" 
                            @click="handleReject(currentDetail)">
                            拒绝
                        </el-button>
                        <el-button 
                            type="info" 
                            @click="backToList">
                            关闭
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 上层基础信息 -->
            <div class="base-info">
                <el-descriptions :column="3" border>
                    <el-descriptions-item label="工单编号">{{ currentDetail.orderNumber }}</el-descriptions-item>
                    <el-descriptions-item label="申请人">{{ currentDetail.createBy }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ currentDetail.createTime }}</el-descriptions-item>
                    <!-- <el-descriptions-item label="审批人">{{ getApprovalUsers(currentDetail.id) }}</el-descriptions-item> -->
                    <el-descriptions-item label="审批人">{{ getApprovalUsers(currentDetail.users) }}</el-descriptions-item>
                    <el-descriptions-item label="审批状态">
                        <el-tag :type="getStatusTagType(currentDetail.status)">
                            {{ getStatusText(currentDetail.status) }} 
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="审批时间">{{ currentDetail.approvalTime || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="批次号" :span="currentDetail.status === '3' ? 1 : 2">
                        {{ currentDetail.batchNumber || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="拒绝原因" v-if="currentDetail.status === '3'">
                        <span style="color: #F56C6C">{{ currentDetail.rejectReason || '无' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <div class="apply-remark">
                    <div class="label">申请原因：</div>
                    <div class="content">{{ currentDetail.remark }}</div>
                </div>
            </div>

            <!-- 下层内容区 -->
            <div class="detail-content">
                <!-- SQL模板内容 -->
                <div class="sql-section">
                    <div class="section-header">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>SQL内容</span>
                        
                        <!-- 展示 附件名称 ；蓝色-->
                        <span v-if="currentDetail.attachmentName" style="color: #409EFF; margin-left: 10px;">
                            附件名称：{{ currentDetail.attachmentName }}
                        </span>
                    </div>
                    <div class="sql-container">
                        <pre class="sql-content">{{ currentDetail.sql }}</pre>
                    </div>
                </div>

                <!-- 审批进度 -->
                <div class="approval-section">
                    <div class="section-header">
                        <el-icon>
                            <Clock />
                        </el-icon>
                        <span>审批进度</span>
                    </div>
                    <div class="progress-container">
                        <div class="progress-item" :class="{ active: true }">
                            <div class="step-icon">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                            </div>
                            <div class="step-content">
                                <div class="step-title">申请提交</div>
                                <div class="step-time">{{ currentDetail.createTime }}</div>
                                <div class="step-desc">申请人：{{ currentDetail.createBy }}</div>
                            </div>
                        </div>

                        <div class="progress-item" :class="{ active: currentDetail.status !== '1', 'status-rejected': currentDetail.status === '3' }">
                            <div class="step-icon">
                                <el-icon>
                                    <Checked />
                                </el-icon>
                            </div>
                            
                            <div class="step-content">
                                <div class="step-title" :class="{ 'step-title-active': currentDetail.status !== '1' }" 
                                :style="{ color: currentDetail.status === '3' ? '#F56C6C' : '' }">
                                    {{ currentDetail.status === '1' ? '待审批' :
                                    currentDetail.status === '2' ? '审批通过' : '审批拒绝' }}
                                </div>
                                <div class="step-time" v-if="currentDetail.approvalTime" 
                                :class="{ 'step-time-active': currentDetail.status !== '1' }" 
                                :style="{ color: currentDetail.status === '3' ? '#F56C6C' : '' }">
                                    {{ currentDetail.approvalTime }}
                                </div>
                                <div class="step-desc" v-if="currentDetail.status === '3'"
                                :class="{ 'step-desc-active': currentDetail.status !== '1' }" 
                                :style="{ color: currentDetail.status === '3' ? '#F56C6C' : '' }">
                                    拒绝原因：{{ currentDetail.rejectReason || '无' }}
                                </div>
                                <div class="step-desc" v-if="currentDetail.status === '2' || 
                                    currentDetail.status === '1' && currentDetail.users"
                                    :class="{ 'step-desc-active': currentDetail.status !== '1' }" 
                                    :style="{ color: currentDetail.status === '3' ? '#F56C6C' : '' }">
                                    审批人：{{ getApprovalUsers(currentDetail.users) }}
                                </div>
                            </div>
                        </div>

                        <div class="progress-item"
                            :class="{ active: currentDetail.status === '2' && currentDetail.batchNumber }"
                            v-if="currentDetail.status === '2'">
                            <div class="step-icon">
                                <el-icon>
                                    <Download />
                                </el-icon>
                            </div>
                            <div class="step-content">
                                <div class="step-title">数据提取</div>
                                <div class="step-time" v-if="currentDetail.batchNumber">
                                    批次号：{{ currentDetail.batchNumber }}
                                </div>
                                <!-- <div class="step-desc">
                                    <el-button type="text" v-if="currentDetail.batchNumber">
                                        前往下载中心
                                    </el-button>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>

        <!-- SQL预览对话框 -->
        <el-dialog v-model="previewDialogVisible" title="SQL预览" width="70%">
          <el-input 
            type="textarea" 
            v-model="previewSql" 
            :rows="15" 
            readonly
            style="margin-bottom: 20px"
          />
          <template #footer>
            <el-button @click="previewDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="handlePreExecute"
              :loading="preExecLoading"
            >
              预执行SQL
            </el-button>
          </template>
        </el-dialog>

        <!-- 取数申请对话框 -->
        <el-dialog v-model="applyDialogVisible" title="取数申请" width="50%">
            <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="100px">
                <el-form-item label="工单编号" prop="orderNumber">
                    <el-input v-model="applyForm.orderNumber" placeholder="请输入工单编号"></el-input>
                    <!-- 选择第三方系统工单编号 -->
                    <el-button style="margin-top: 10px;" link type="primary" @click="handleSelectOrderNumber">选择工单编号</el-button>
                </el-form-item>
                <el-form-item label="审批人" prop="userId">
                    <el-select v-model="applyForm.userId" placeholder="请选择审批人" style="width: 100%">
                        <el-option v-for="user in provinceUsers" :key="user.userId" :label="user.userName"
                            :value="user.userId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="申请原因" prop="remark">
                    <el-input type="textarea" v-model="applyForm.remark" :rows="3"
                        placeholder="请输入申请原因"></el-input>
                </el-form-item>
                <!-- 增加一个条数限制 默认加载 不能修改-->
                <el-form-item label="条数限制" prop="rowLimit">
                    <el-input v-model="applyForm.rowLimit" placeholder="请输入条数限制" disabled></el-input>
                </el-form-item>
                <el-form-item label="取数模板" prop="templateId">
                    <el-select @change="handleTemplateChange" v-model="applyForm.templateId" placeholder="请选择取数模板" style="width: 100%">
                        <el-option v-for="template in templates" :key="template.id" :label="template.templateName"
                            :value="template.id"></el-option>
                    </el-select>
                    <!-- <div style="margin-top: 10px;">
                        <el-link type="primary" @click="showTemplateDialog">新增模板</el-link>
                    </div> -->
                </el-form-item>
                <el-form-item v-if="applyForm.variables.length > 0" label="预设变量" prop="variables">
                    <div class="variables-container">
                        <div v-for="(variable, index) in applyForm.variables" :key="index" class="variable-item">
                            <el-row :gutter="10" style="margin-bottom: 10px;">
                                <el-col :span="9">
                                    <el-form-item style="margin-left: -50px;"
                                    label="字段名"
                                    :prop="`variables.${index}.fieldName`">
                                        <el-input disabled v-model="variable.fieldName" placeholder="变量字段名" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="11">
                                    <el-form-item
                                        label="字段描述" 
                                        :prop="`variables.${index}.remark`">
                                            <el-input disabled v-model="variable.remark" placeholder="变量字段描述" />
                                    </el-form-item>
                                </el-col>    
                                <el-col :span="9">
                                <el-form-item style="margin-left: -50px;margin-top: 10px;"
                                label="字段类型"
                                :prop="`variables.${index}.fieldType`">
                                    <el-select disabled v-model="variable.fieldType" placeholder="字段类型" style="width: 100%">
                                        <el-option label="字符串" value="string" />
                                        <el-option label="数字" value="number" />
                                        <el-option label="日期" value="date" />
                                    </el-select>
                                </el-form-item>
                                </el-col>
                                <el-col :span="11">
                                <el-form-item style="margin-top: 10px;"
                                label="是否必填"
                                :prop="`variables.${index}.required`">
                                <el-select disabled v-model="variable.required" placeholder="是否必填" 
                                style="width: 100%">
                                    <el-option label="是" value="1" />
                                    <el-option label="否" value="0" />
                                </el-select>
                                </el-form-item>
                                </el-col>
                                <el-col :span="11" style="margin-left: -50px;margin-top: 10px;">
                                    <el-form-item 
                                        label="运算符"
                                        :rules="variable.required === '1' ? [
                                            { required: true, message: '请选择操作符', trigger: 'change' }
                                        ] : []"
                                        :prop="`variables.${index}.operator`">
                                        <el-select v-model="variable.operator" placeholder="运算符" style="width: 95%">
                                            <el-option label="等于" value="=" />
                                            <el-option label="不等于" value="!=" />
                                            <el-option label="大于" value=">" />
                                            <el-option label="大于等于" value=">=" />
                                            <el-option label="小于" value="<" />
                                            <el-option label="小于等于" value="<=" />
                                            <el-option label="介于" value="between" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col style="margin-top: 10px;margin-left: -11px;" :span="11" v-if="variable.fieldType !== 'date' && variable.operator !== 'between'">
                                    <el-form-item
                                    :label="variable.fieldType === 'string' ? '字段值' : '字段值(数字)'" 
                                    :prop="`variables.${index}.value`"
                                    style="margin-bottom: 10px;"
                                    :rules="variable.required === '1' ?[
                                        { required: true, message: '请输入字段值', trigger: 'blur' }
                                    ] : []">
                                        <el-input class="custom-input" v-model="variable.value" placeholder="字段值"/>
                                    </el-form-item>
                                </el-col>

                                <el-col style="margin-top: 10px;margin-left: -11px;" :span="11" v-if="variable.fieldType !== 'date' && variable.operator === 'between'">
                                    <!-- 等于 between 展示两个 values -->
                                    <el-form-item 
                                    :label="variable.fieldType ==='string'? '开始值' : '开始值(数字)'"
                                    :prop="`variables.${index}.startValue`"
                                    style="margin-bottom: 10px;"
                                    :rules="variable.required === '1' ?[
                                        { required: true, message: '请输入开始值', trigger: 'blur' }
                                    ] : []">
                                        <el-input class="custom-input" v-model="variable.startValue" placeholder="请输入开始值"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="9" v-if="variable.fieldType !== 'date' && variable.operator === 'between'">
                                    <!-- 等于 between 展示两个 values -->
                                    <el-form-item 
                                    :label="variable.fieldType ==='string'? '结束值' : '结束值(数字)'"
                                    :prop="`variables.${index}.endValue`"
                                    style="margin-bottom: 10px;margin-top: 10px;margin-left: -50px;"
                                    :rules="variable.required === '1' ?[
                                        { required: true, message: '请输入结束值', trigger: 'blur' }
                                    ] : []">
                                        <el-input class="custom-input" v-model="variable.endValue" placeholder="请输入结束值"/>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="11" style="margin-left: -10px;" v-if="variable.fieldType === 'date' && variable.operator !== 'between'">
                                    <el-form-item 
                                        label="日期"
                                        style="margin-top: 10px;margin-bottom: 10px;"
                                        :rules="variable.required === '1' ? [
                                            { required: true, message: '请选择日期', trigger: 'change' }
                                        ] : []"
                                        :prop="`variables.${index}.date`">
                                        <el-date-picker 
                                            v-model="variable.date" 
                                            type="date" 
                                            placeholder="选择日期" 
                                            style="width: 100%"
                                            value-format="YYYY-MM-DD" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12" style="margin-left: -10px;" v-if="variable.fieldType === 'date' && variable.operator === 'between'">
                                    <el-form-item 
                                        label="日期范围"
                                        style="margin-top: 10px;margin-bottom: 10px;"
                                        :rules="variable.required === '1' ? [
                                            { required: true, message: '请选择日期范围', trigger: 'change' }
                                        ] : []"
                                        :prop="`variables.${index}.dateRange`">
                                        <el-date-picker 
                                            v-model="variable.dateRange" 
                                            type="daterange" 
                                            range-separator="至"
                                            start-placeholder="开始日期" 
                                            end-placeholder="结束日期" 
                                            style="width: 100%"
                                            value-format="YYYY-MM-DD" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </el-form-item>

              <el-form-item label="临时表数据" prop="fileList">
                <el-upload style="width: 800px;" :limit="1" accept=".txt" :auto-upload="false" drag multiple
                           @change="handleFileChange"
                           @remove="handleFileRemove"
                           :file-list="applyForm.fileList">
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <template #tip>
                    <div class="el-upload__tip text-center">
                      <span>仅允许导入.txt格式文件。</span>
                      <el-button link type="primary" @click="downloadTempTableTemplate">下载模板</el-button>
                    </div>
                  </template>
                  <!-- 当tempTableName不为空的时候 显示临时表名 字体显示成红色 -->
<!--                  <div v-if="applyForm.tempTableName" style="color: red;" class="temp-table-name">-->
<!--                    临时表名：{{ applyForm.tempTableName }}-->
<!--                  </div>-->
                </el-upload>
              </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="applyDialogVisible = false">取 消</el-button>
                    <el-button 
                        type="primary" 
                        @click="handlePreviewSql"
                        :loading="preExecLoading"
                        >
                        生成SQL并预执行
                    </el-button>
                    <el-button 
                        type="success" 
                        @click="submitApply"
                        :disabled="!isSqlPreExecuted"
                        >
                        提交申请
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 第三方工单系统编号选择对话框 -->
        <el-dialog v-model="selectOrderDialogVisible" title="选择工单系统编号" width="40%">
            <el-form :model="selectOrderForm" ref="selectOrderFormRef" label-width="100px">
                <el-form-item label="工单编号" prop="orderNumber">
                    <el-select v-model="selectOrderForm.orderNumber" placeholder="请选择工单编号"
                        style="width: 100%">
                        <el-option v-for="order in orders" :key="order.id" :label="order.orderNumber"
                            :value="order.orderNumber"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleSelectOrderCancel">取 消</el-button>
                    <el-button type="primary" @click="handleSelectOrder">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 审批对话框 -->
        <el-dialog v-model="approvalDialogVisible" title="审批取数申请" width="40%">
            <el-form :model="approvalForm" ref="approvalFormRef" :rules="approvalRules" label-width="100px">
                <el-form-item label="审批状态" prop="status">
                    <el-radio-group v-model="approvalForm.status">
                        <el-radio label="2">通过</el-radio>
                        <el-radio label="3">拒绝</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="approvalForm.status === '3'" label="拒绝原因" prop="rejectReason">
                    <el-input type="textarea" v-model="approvalForm.rejectReason" :rows="3"
                        placeholder="请输入拒绝原因"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleApprovalClose">取 消</el-button>
                    <el-button type="primary" @click="submitApproval">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 审批拒绝对话框 -->
        <el-dialog v-model="rejectDialogVisible" title="审批拒绝" width="40%">
            <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules" label-width="100px">
                <el-form-item label="拒绝原因" prop="rejectReason">
                    <el-input type="textarea" v-model="rejectForm.rejectReason" :rows="3"
                        placeholder="请输入拒绝原因"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="rejectDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitReject">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="FetchApply">
import { listByDept } from "@/api/system/user";
import {
   listTemplateAll
} from "@/api/tempcfg/templatecfg/templatecfg";
import { apply, list, approve, detail, generateSql, preExecuteSql } from "@/api/zhreport/fetchapply/fetchapply";
import useUserStore from '@/store/modules/user';
import { listVariable } from "@/api/tempcfg/templatecfg/variable";
import { ElMessageBox } from 'element-plus';    
import { getConfigKey } from "@/api/system/config";

const { proxy } = getCurrentInstance();

// 是否显示详情页
const showDetail = ref(false);

// SQL预览相关状态
const previewDialogVisible = ref(false);
const previewSql = ref('');
const isSqlPreExecuted = ref(false);
const preExecLoading = ref(false);

// 当前详情数据
const currentDetail = ref({});

const filteredData = ref([]);

// 标签页
const activeTab = ref('pending')

// 分页
const pagination = reactive({
    current: 1,
    size: 10,
    total: 10
})

// 搜索表单
const searchForm = reactive({
    pageNum: 1,
    pageSize: 10
})


// 取数模板
const templates = ref([])

// 申请对话框
const applyDialogVisible = ref(false)
const applyFormRef = ref(null)
const applyForm = reactive({
    orderNumber: 'GD' + new Date().getTime(),
    userId: undefined,
    remark: '',
    templateId: undefined,
    tempTableName: '',
    userIds: [],
    fileList: [],
    variables: [],
    rowLimit: undefined
})

const applyRules = reactive({
    orderNumber: [{ required: true, message: '请输入工单编号', trigger: 'change' }],
    userId: [{ required: true, message: '请选择审批人', trigger: 'change' }],
    remark: [{ required: true, message: '请输入申请原因', trigger: 'blur' }],
    templateId: [{ required: true, message: '请选择取数模板', trigger: 'change' }]
})

// 第三方工单系统编号选择对话框
const selectOrderDialogVisible = ref(false)
const selectOrderFormRef = ref(null)
const selectOrderForm = reactive({
    orderNumber: ''
})
// 模拟第三方系统工单编号数据
const orders = ref([
    {
        id: 1,
        orderNumber: 'GD20230001'
    },
    {
        id: 2,
        orderNumber: 'GD20230002'
    },
    {
        id: 3,
        orderNumber: 'GD20230003'
    } 
])

// 省公司人员数据
const provinceUsers = ref([])

// 审批对话框
const approvalDialogVisible = ref(false)
const approvalFormRef = ref(null)

const approvalForm = ref({
    status: '2'
})

// 设置审批对话框必填校验
const approvalRules = {
    status: [
        { required: true, message: '请选择审批状态', trigger: 'change' }
    ],
    rejectReason: [
        { required: true, message: '请输入拒绝原因', trigger: 'blur' }
    ] 
}

// 获取 user store 实例
const userStore = useUserStore();

// 审批拒绝变量
const rejectForm = reactive({
    rejectReason: ''
})
const rejectFormRef = ref(null);
const rejectRules = {
    rejectReason: [
        { required: true, message: '请输入拒绝原因', trigger: 'blur' }
    ] 
}
const rejectDialogVisible = ref(false);


// 标签页切换
const handleTabChange = (tab, event) => {
    // 获取当前标签页的值
    activeTab.value = tab.paneName;
    pagination.current = 1
    getList();
}

// 获取状态文本
const getStatusText = (status) => {
    const map = {
        '1': '待审批',
        '2': '已通过',
        '3': '已拒绝'
    }
    return map[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
    const map = {
        '1': 'warning',
        '2': 'success',
        '3': 'danger'
    }
    return map[status] || ''
}

// 获取审批人
const getApprovalUsers = (users) => {
    return users[0].userName;
}

// 搜索
const handleSearch = () => {
    pagination.current = 1
    getList();
}

// 重置搜索
const resetSearch = () => {
    searchForm.orderNumber = undefined;
    searchForm.userId = undefined;
    searchForm.batchNumber = undefined;
    searchForm.status = undefined;
    searchForm.createTimeRange = [];
    searchForm.approvalTimeRange = [];
    pagination.current = 1;
    getList();
}

// 显示申请对话框
const showApplyDialog = async () => {
    await getConfigKey('qs_data_limit').then(res => {
        if (res.code === 200) {
            applyForm.rowLimit = res.msg;
        } else {
            proxy.$modal.msgError(res.msg);
        }
    })
    // 重置表单
    proxy.resetForm("applyFormRef");
    applyForm.variables = [];
    // 模拟获取工单编号
    applyForm.orderNumber = 'GD' + new Date().getTime();
    getTemplates();
    applyDialogVisible.value = true;
    isSqlPreExecuted.value = false;
}

async function handlePreviewSql() {
    applyFormRef.value.validate(async valid => {
        if (valid) {
            try {
                applyForm.userIds = [applyForm.userId];
                // 根据类型过滤掉变量中的value、date、dateRange为空的数据
                applyForm.variablesList = applyForm.variables.filter(variable => {
                    if (variable.fieldType === 'date') {
                        if (variable.operator === 'between') {
                            return variable.dateRange && variable.dateRange.length > 0; 
                        } else {
                            return variable.date;
                        }
                    } else {
                        return variable.value || (variable.startValue && variable.endValue);
                    }
                })
                preExecLoading.value = true;
                const response = await generateSql(applyForm); // 调用生成SQL接口
                previewSql.value = response.data;
                previewDialogVisible.value = true;
            } finally {
                preExecLoading.value = false;
            }
        }
    });
}

async function handlePreExecute() {
  try {
    preExecLoading.value = true;
    applyForm.previewSql = previewSql.value;
    await preExecuteSql(applyForm); // 调用预执行接口
    isSqlPreExecuted.value = true;
    proxy.$modal.msgSuccess('SQL预执行成功');
    previewDialogVisible.value = false;
  } finally {
    preExecLoading.value = false;
  }
}

// 提交申请
async function submitApply() {
  if (!isSqlPreExecuted.value) {
    proxy.$modal.msgWarning('请先预执行SQL并确保成功');
    return;
  }
  
  applyFormRef.value.validate(valid => {
    if (valid) {
      const formData = new FormData();
      // 文件
      if (applyForm.fileList.length > 0) {
        // applyForm.attachment = applyForm.fileList[0].raw;
        formData.append('file', applyForm.fileList[0].raw);
      }

      // 添加 JSON 数据
      const jsonData = JSON.stringify(applyForm);
      const blob = new Blob([jsonData], { type: 'application/json' });
      formData.append('request', blob);
      console.log("formData",formData);
      // variablesList: applyForm.variablesList.map(v => ({
      //   createBy: v.createBy,
      //   createTime: v.createTime,
      //   updateBy: v.updateBy,
      //   updateTime: v.updateTime,
      //   remark: v.remark,
      //   id: v.id,
      //   templateId: v.templateId,
      //   fieldName: v.fieldName,
      //   fieldType: v.fieldType,
      //   required: v.required,
      //   delFlag: v.delFlag,
      //   operator: v.operator,
      //   value: v.value
      // }));
      // applyForm.variablesList = null;
        apply(formData).then(res => {
        proxy.$modal.msgSuccess('申请提交成功');
        applyDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgSuccess('申请提交失败');
      });
    } 
  })
}

// 显示详情页
const showDetailView = (row) => {
    // 调用接口获取详情数据
    getDetail(row.id);
}

function getDetail(id) {
    detail(id).then(res => {
        currentDetail.value = res.data;
        showDetail.value = true;
    })
}

function handleFileChange(file, fileList) {
  // 检查文件扩展名
  const allowedExtensions = ['.txt'];
  const extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();

  if (!allowedExtensions.includes(extension)) {
    proxy.$modal.msgError('只允许上传.txt格式文件');
    applyForm.fileList = [];
    return false;
  } else {
    // 更新 form.fileList 的值
    applyForm.fileList = fileList;
    // 生成一个临时表名
    if (fileList.length > 0) {
      let time = formatTimestamp();
      // 使用格式化函数生成临时表名
      applyForm.tempTableName = "temp_" + time;
    }
  }
}

function handleFileRemove(file, fileList) {
  applyForm.fileList = fileList;
  // 文件删除后清空临时表名
  applyForm.tempTableName = undefined;
}

function downloadTempTableTemplate() {
  proxy.$download.file("/data/template/cfg/temp/table/download", "temp_table_filed_data_template.txt");
}

// 返回列表页
const backToList = () => {
    showDetail.value = false;
    getList();
}

function handleSelectOrderNumber() {
    selectOrderDialogVisible.value = true;
}

function handleSelectOrder() {
    applyForm.orderNumber = selectOrderForm.orderNumber;
    selectOrderDialogVisible.value = false;
}

function handleSelectOrderCancel() {
    selectOrderDialogVisible.value = false;
    // 清空选择的工单编号
    selectOrderForm.orderNumber = '';
}

// 查询省公司人员数据
function getProvinceUsers() {
    let query = {
        deptId: 100
    }
  listByDept(query).then(res => {
        provinceUsers.value = res.data;
    })
}
getProvinceUsers();

// 添加格式化函数
const formatTimestamp = () => {
  const date = new Date(Date.now());
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  const milliseconds = String(date.getMilliseconds()).padStart(3, '0').slice(0, 2);
  return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
};

// 查询模板数据
function getTemplates() {
    let query = {
        isEnable: '1'
    }
    listTemplateAll(query).then(res => {
        templates.value = res.data;
    })
}

// 查询数据
function getList() {
    let query = {
        pageNum: pagination.current,
        pageSize: pagination.size,
        orderNumber: searchForm.orderNumber,
        userId: searchForm.userId,
        batchNumber: searchForm.batchNumber,
        createStartTime: searchForm.createTimeRange ? searchForm.createTimeRange[0] : undefined,
        createEndTime: searchForm.createTimeRange ? searchForm.createTimeRange[1] : undefined,
        approvalStartTime: searchForm.approvalTimeRange ? searchForm.approvalTimeRange[0] : undefined,
        approvalEndTime: searchForm.approvalTimeRange ? searchForm.approvalTimeRange[1] : undefined,
    }
    
    // 判断标签页
    if (activeTab.value === 'pending') {
        query.status = ['1'];
    } else if (activeTab.value === 'completed') {
        query.status = ['2', '3'];
    } else {
        query.status = undefined;
    }
    
    list(query).then(res => {
        // 更新分页总数
        pagination.total = res.total;
        filteredData.value = res.rows;
    })
}


function handleSizeChange(size) {
    pagination.size = size;
    getList();
}

function handleCurrentChange(current) {
    pagination.current = current;
    getList();
}

// 显示审批对话框
const showApprovalDialog = (row) => {
    approvalDialogVisible.value = true
    // 重置表单
    proxy.resetForm("approvalFormRef"); 
    approvalForm.value.id = row.id;
}

function handleApprovalClose() {
    approvalDialogVisible.value = false;
    // 重置表单
    proxy.resetForm("approvalFormRef");
}

function submitApproval() {
    approvalFormRef.value.validate(valid => {
        if (valid) {
            approve(approvalForm.value).then(res => {
                if (approvalForm.value.status === '2') {
                    proxy.$modal.msgSuccess('审批成功，批次号为：' + res.data + '，请等待数据提取完成前往文件下载中心下载！');
                    approvalDialogVisible.value = false;
                } else {
                    proxy.$modal.msgSuccess('审批成功!');
                    approvalDialogVisible.value = false;
                }
                getList();
            })
        } 
    })
}

function isApprovalUser(users) {
    // 提取审批人ID列表
    const userIds = users.map(user => user.userId);
    // 检查当前用户是否在审批人列表中
    return userIds.includes(userStore.id);
}

getList();

function handleTemplateChange(value) {
    // 当模板ID改变时，查询并且更新模板对应的变量列表
    listVariable({
        templateId: value,
        // required: '1'
    }).then(res => {
        applyForm.variables = res.data;
        // 提交申请设置false
        isSqlPreExecuted.value = false;
    })
}

// 审批通过按钮
function handleApprove(detail) {
    // 提示confim 对话框，确认后调用接口
    ElMessageBox.confirm('是否确认通过该取数申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 确认通过，执行审批通过操作
        const data = {
            id: detail.id,
            status: '2'
        }
        approve(data).then(res => {
            proxy.$modal.msgSuccess('审批成功，批次号为：' + res.data + '，请等待数据提取完成前往文件下载中心下载！');
            approvalDialogVisible.value = false;
            getDetail(detail.id);
        })
    })
}

function handleReject(detail) {
    // 重置表单
    proxy.resetForm("rejectFormRef");
    // 赋值
    rejectForm.id = detail.id;
    rejectDialogVisible.value = true;
}

function submitReject() {
    rejectFormRef.value.validate(valid => {
        if (valid) {
            const data = {
                id: rejectForm.id,
                status: '3',
                rejectReason: rejectForm.rejectReason
            }
            approve(data).then(res => {
                proxy.$modal.msgSuccess('审批成功!');
                rejectDialogVisible.value = false;
                getDetail(rejectForm.id);
            })
        } 
    }) 
}

</script>

<style scoped>
.data-apply-container {
    padding: 20px;
}

.operation-area {
    margin-bottom: 20px;
}

.filter-area {
    margin-bottom: 20px;
}

.pagination-area {
    margin-top: 20px;
    text-align: right;
}

.el-tabs {
    margin-top: 20px;
}

.el-table {
    margin-top: 20px;
}

/* 详情页样式 */
.detail-card {
    margin-bottom: 20px;
}

.detail-header {
    display: flex;
    align-items: center;
    padding: 10px 20px;
}

.detail-header span {
    margin-left: 15px;
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.base-info {
    padding: 20px;
    background: #f9f9f9;
    border-radius: 4px;
    margin-bottom: 20px;
}

.apply-remark {
    margin-top: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
}

.apply-remark .label {
    font-weight: bold;
    margin-bottom: 8px;
    color: #666;
}

.apply-remark .content {
    line-height: 1.6;
    color: #333;
}

.detail-content {
    display: flex;
    gap: 20px;
}

.sql-section,
.approval-section {
    flex: 1;
}

.section-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.section-header i {
    margin-right: 8px;
    color: #409EFF;
}

.section-header span {
    font-size: 16px;
    font-weight: bold;
    color: #333;
}

.sql-container {
    height: 400px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 15px;
    background: #f5f7fa;
    overflow: auto;
}

.sql-content {
    margin: 0;
    font-family: Consolas, Monaco, monospace;
    font-size: 14px;
    line-height: 1.5;
    color: #333;
    white-space: pre-wrap;
}

.progress-container {
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background: #f5f7fa;
}

.progress-item {
    display: flex;
    padding: 15px 0;
    position: relative;
}

.progress-item:not(:last-child)::after {
    content: '';
    position: absolute;
    left: 19px;
    top: 40px;
    bottom: -5px;
    width: 2px;
    background: #dcdfe6;
}

.progress-item.active:not(:last-child)::after {
    background: #409EFF;
}

.step-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #dcdfe6;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    flex-shrink: 0;
    color: #fff;
}

.progress-item.active .step-icon {
    background: #409EFF;
}

.progress-item.status-rejected .step-icon{
    background-color: #F56C6C;
}

.step-icon i {
    font-size: 18px;
}

.step-content {
    flex: 1;
}

.step-title {
    font-weight: bold;
    margin-bottom: 5px;
    color: #606266;
}

.progress-item.active .step-title {
    color: #409EFF;
}

.step-time {
    font-size: 13px;
    color: #909399;
    margin-bottom: 5px;
}

.step-desc {
    font-size: 13px;
    color: #666;
    line-height: 1.5;
}

.search-form-container {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 12px 16px;
}

.form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.form-item :deep(.el-form-item__label) {
  width: 80px !important;
  text-align: right;
  padding-right: 12px;
  flex-shrink: 0;
}

.form-item :deep(.el-form-item__content) {
  flex: 1;
  min-width: 0;
}

/* .form-actions {
  margin-left: auto;
  padding-top: 2px;
} */

/* 响应式调整 */
@media (max-width: 1600px) {
  .search-form-container {
    gap: 12px;
  }
  
  .form-item :deep(.el-form-item__label) {
    width: 70px !important;
  }
  
  .form-item :deep(.el-date-editor) {
    width: 240px !important;
  }
}

.custom-input {
    width: 500px !important;
}
</style>